#
# peerscape.daemon.register
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
User Registration

Peerscape maintains a "Peerscape Users" dataset containing names and
IIDs.  This enables directory services to discover and cache the
profiles of new users who have no friendships or memberships yet.
"""

import time
import logging

from peerscape import DB
from peerscape.db.util import get_timestamp

IID = '57453a4b85508565d9cf63ab5457fb73f456f24c'
INTERVAL = 2.0

class RegistrationAgent(object):
    def __init__(self, path):
        self.path = path
        self.subscribed = False

    def loop(self):
        while True:
            try:
                self.update()
                time.sleep(INTERVAL)
            except Exception:
                logging.exception('Exception in registration agent:')
                time.sleep(60)

    def update(self):
        db = DB(self.path, create=False)
        try:
            self.update_registration(db)
        finally:
            db.close()

    def update_registration(self, db):
        if not self.subscribed:
            db.subscribe(IID)
            self.subscribed = True

        try:
            iid = db.get_my_iid()
        except LookupError:
            return

        info = db.get_json(IID, ['people', iid])
        if not info and not db.get(IID, '/info/modified'):
            return

        name = db.get_profile_name(iid)
        if name is None:
            return

        if not info or info.get('name') != name:
            logging.info('Updating registration.')

            now = get_timestamp()
            if info:
                info['updated'] = now
            else:
                info = {'created': now}

            info['name'] = name
            try:
                db.put(IID, ['people', iid], info)
            except LookupError:
                pass
